<template>
  <el-dialog
    title="上传文件"
    :visible.sync="visible"
    width="500px"
    @close="onClose"
    v-loading="loading" 
    element-loading-text="正在上传中，请稍候..."  
    element-loading-spinner="el-icon-loading"
  >
    <div style="margin-bottom: 20px;">
      <el-alert
        type="info"
        :closable="false"
        :title="fileType === 'video' ? '请上传 MP4 视频文件' : '请上传 PDF 文件'"
      ></el-alert>
    </div>

    <el-upload
      :file-list="fileList"
      :auto-upload="false"
      :limit="1"
      accept=".mp4,.pdf"
      :on-change="handleFileChange"
      :on-remove="handleRemove"
    >
      <el-button type="primary">选择文件</el-button>
    </el-upload>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="uploadFile">上传</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      lessonId: null,
      fileType: "video", // "video" or "pdf"
      file: null,
      fileList: [],
      durationSeconds: null,
      uploadUrl:null,
      loading: false
    };
  },
  methods: {
    // 打开弹窗并初始化参数
    open(id, type, currentUrl = null) {
      this.lessonId = id;
      this.fileType = type;
      this.visible = true;
      this.file = null;
      this.fileList = [];
      this.durationSeconds = null;
    },

    // 文件选择事件
    handleFileChange(file) {
      this.file = file.raw;
    },

    // 移除文件
    handleRemove() {
      this.file = null;
    },

    // 上传文件方法
    uploadFile() {
      if (!this.file) {
        this.$message.warning("请先选择文件");
        return;
      }

      const formData = new FormData();
      formData.append("file", this.file);
      formData.append("lessonId", this.lessonId);


        if (this.fileType == 'video') {
            this.uploadUrl = "api/upload/lesson/video";
        }
        else {
            this.uploadUrl = "api/upload/lesson/pdf";
        }

        this.loading = true;
      this.$http({
        url:this.uploadUrl,
        method: "post",
        body: formData,
      }).then(({ data }) => {
        this.loading = false;
        if (data && data.code === 0) {
          this.$message.success("上传成功");
          this.visible = false;

          this.$emit("uploaded"); // 通知父组件刷新数据
        } else {
          this.$message.error(data.msg || "上传失败");
        }
      }).catch(error => {
        this.loading = false;
        console.error("上传错误:", error);
        this.$message.error("上传出错，请稍后再试");
      });
    },

    onClose() {
      this.file = null;
      this.fileList = [];
      this.durationSeconds = null;
      this.$emit("dialogClosed");
    }
  }
};
</script>
